/*
 * @Author: hcluo
 * @Date: 2020-08-29 10:19:03
 * @LastEditors: hcluo
 * @LastEditTime: 2020-08-30 14:58:10
 * @Description:
 */
import React, { useState, useEffect } from 'react';
// import PropTypes from 'prop-types';

import { useRequest } from './redux/hooks';

import { Tree } from '@wind/wind-ui';

const TreeNode = Tree.TreeNode;

const findNode = (data, id) => {
  let result = {};
  const loop = (data, id, parent = data) => {
    data.forEach((item, index) => {
      if (item.id === id) {
        result = { item, index, parent, data };
      }
      if (item.children && item.children.length) {
        loop(item.children, id, item);
      }
    });
  };

  loop(data, id, data);
  return result;
};

export default function LeftSide1() {
  const [remoteData, status] = useRequest('./api/costomSelectors.json', {}, []);

  const [data, setData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);

  useEffect(() => {
    let b = checkedKeys.length;
    window.LeftToolEnable(!!b);
  }, [checkedKeys]);

  useEffect(() => {
    setData(remoteData);
  }, [remoteData, setData]);

  const loop = data =>
    data.map(item => {
      if (item.children && item.children.length) {
        return (
          <TreeNode key={item.id} title={item.name}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          key={item.id}
          title={item.name}
          // onClick={() => {
          //   window.RightGetData(item.id);
          // }}
        />
      );
    });

  const onDrop = info => {
    const dropKey = info.node.props.eventKey; //目标节点的key
    const dragKey = info.dragNode.props.eventKey; //被拖动节点的key
    const dropPos = info.node.props.pos.split('-'); //目标位置
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    //(一个中间变量，如果放置的是目标节点的上边，值为目标节点index-1,反之+1)-(目标节点index)(得到dropPosition为1/-1/0)
    const loop = (nodeData, key, callback) => {
      //公共方法，遍历节点执行回调
      nodeData.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    const TData = [...data];
    let dragObj;
    loop(TData, dragKey, (item, index, arr) => {
      //data中去掉被拖动节点并保存到dragObj
      arr.splice(index, 1);
      dragObj = item;
    });
    if (info.dropToGap) {
      //放入两个节点之间
      let ar;
      let i; //记录去掉被拖动元素后，目标节点下标
      loop(TData, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        //dropPosition为-1代表放到目标节点上边（在目标节点处插入）
        ar.splice(i, 0, dragObj);
      } else {
        //dropPosition为1，代表放到目标节点下边（在目标节点下一位置插入）
        ar.splice(i + 1, 0, dragObj);
      }
    } else {
      //拖到节点上（作为目标节点child）
      loop(TData, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到尾部，可以是随意位置
        item.children.push(dragObj);
      });
    }
    setData(TData);
  };

  const renameBlock = name => {
    let res = findNode(data, checkedKeys[0]);
    res.item.name = name;
    console.log(
      '%c 🥝 res.item: ',
      'font-size:20px;background-color: #ED9EC7;color:#fff;',
      res.item,
      data,
    );
    setData(JSON.parse(JSON.stringify(data)));
  };

  const addBlock = name => {
    data.push({ name, id: (Math.random() * 1000000).toFixed(0) });
    setData(JSON.parse(JSON.stringify(data)));
  };

  const addChildBlock = (name, type = 1, noUpdate = false) => {
    let res = findNode(data, checkedKeys[0]);
    if (res.item.children && Array.isArray(res.item.children)) {
      if (type === 1) res.item.children.unshift({ name, id: (Math.random() * 1000000).toFixed(0) });
      else res.item.children.push({ name, id: (Math.random() * 1000000).toFixed(0) });
    } else {
      res.item.children = [{ name, id: (Math.random() * 1000000).toFixed(0) }];
    }

    !noUpdate && setData(JSON.parse(JSON.stringify(data)));
  };

  const deleteBlock = (noUpdate = false) => {
    let res = findNode(data, checkedKeys[0]);
    if (Array.isArray(res.parent)) {
      //根节点数组
      data.filter(item => item.id !== checkedKeys[0]);
      !noUpdate && setData(JSON.parse(JSON.stringify(data)));
    } else {
      res.parent.children = res.parent.children.filter(item => item.id !== checkedKeys[0]);
      !noUpdate && setData(JSON.parse(JSON.stringify(data)));
    }
  };

  const moveBlock = type => {
    let res = findNode(data, checkedKeys[0]);

    if (Array.isArray(res.parent)) {
      //根节点数组
      setData(JSON.parse(JSON.stringify(data.filter(item => item.id !== checkedKeys[0]))));
    } else {
      let index = res.index;
      if (type === -1) {
        if (index < res.parent.children.length) {
          [res.parent.children[index + 1], res.parent.children[index]] = [
            res.parent.children[index],
            res.parent.children[index + 1],
          ];
        }
      } else if (type === 1) {
        if (index > 0) {
          [res.parent.children[index - 1], res.parent.children[index]] = [
            res.parent.children[index],
            res.parent.children[index - 1],
          ];
        } else {
        }
      }
      setData(JSON.parse(JSON.stringify(data)));
    }
  };

  window.LeftSideFunction = (name, type) => {
    switch (type) {
      case 0:
        addBlock(name);
        break;
      case 1:
        addChildBlock(name);
        break;
      case 2:
        renameBlock(name);
        break;
      case 3:
        deleteBlock();
        break;
      case 4:
        moveBlock(name);
        break;
    }
  };

  return (
    <div className="common-left-side-1">
      <Tree
        multiple={false}
        checkedKeys={checkedKeys}
        onSelect={(selectedKeys, e) => {
          if (selectedKeys.length === 1) {
            window.RightGetData(e.selectedNodes[0].key);
          }
          setCheckedKeys(selectedKeys);
          let res = findNode(data, selectedKeys[0]);
        }}
        className="draggable-tree"
        draggable
        // onDragEnter={this.onDragEnter}
        // onDrop={onDrop}
      >
        {loop(data)}
      </Tree>
    </div>
  );
}

LeftSide1.propTypes = {};
LeftSide1.defaultProps = {};
